package com.itheima.mode_test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.Before;
import org.junit.Test;

/**
 * @author ：yuan_he_song
 */
public class DataTest {

    private ZooKeeper zooKeeper;

    @Before
    public void init() throws IOException {
        // 集群逗号链接 192.168.244.128:2181,192.168.244.129:2181
        String connectStr = "192.168.244.128:2181";
        zooKeeper = new ZooKeeper(connectStr, 50000, new Watcher() {
            @Override //监听回调方法
            public void process(WatchedEvent watchedEvent) {
            }
        });
    }

    @Test // 获取节点的数据
    public void getData() throws Exception {
        byte[] bytes = zooKeeper.getData("/tuling", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    zooKeeper.getData("/tuling",this,null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(event.getPath());
            }
        }, null);
        String data = new String(bytes,"utf-8");
        System.out.println("节点的数据: "+data);
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test // 获取/tuling节点的子节点(只是节点名称)
    public void getChild() throws Exception{
        List<String> children = zooKeeper.getChildren("/tuling", false);
        children.stream().forEach(System.out::println);
    }

    @Test // 创建节点
    public void createNode() throws KeeperException, InterruptedException {
        List<ACL> list = new ArrayList<>();
        int perms = ZooDefs.Perms.ALL;
        ACL acl = new ACL(perms,new Id("world","anyone"));
        list.add(acl);
        String path = zooKeeper.create("/heima/server", "good man".getBytes(), list, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(path);
        Thread.sleep(Integer.MAX_VALUE);

    }


}
